import { schedule } from '../core/Scheduler'
import SimulationSpeed from '../core/SimulationSpeed'
import { messageTransfer } from '../messaging/MessageTransfer'
import { simController } from '../simulation/SimController'
import BaseStation from './BaseStation'
import WorkerPool from './WorkerPool'

class Worker {
  id: string
  x: number
  y: number
  target: BaseStation
  workerPool: WorkerPool
  taskType: 'assist' | 'clean' | 'maintenance' | 'return'
  speed: number
  maintenanceTime: number

  targetX: number = 0
  targetY: number = 0

  constructor(
    id: string,
    x: number,
    y: number,
    target: BaseStation,
    workerPool: WorkerPool,
    taskType: 'assist' | 'clean' | 'maintenance',
    speed: number,
    maintenanceTime: number
  ) {
    this.id = id
    this.x = x
    this.y = y
    this.target = target
    this.workerPool = workerPool
    this.taskType = taskType
    this.speed = speed
    this.maintenanceTime = maintenanceTime
  }

  //执行任务
  executeTask() {
    this.targetX = this.target.x
    this.targetY = this.target.y

    if (this.taskType === 'assist') {
      //执行协助任务
      this.moving()
    } else if (this.taskType === 'clean') {
      //执行清洁任务
      this.moving()
    } else if (this.taskType === 'maintenance') {
      //执行维护任务
      this.moving()
    }
  }

  //移动
  moving() {
    if (simController.getStatus() !== 'running') return
    // 计算当前位置和目标位置的距离
    const dx = this.targetX - this.x
    const dy = this.targetY - this.y
    const distanceToTarget = Math.sqrt(dx * dx + dy * dy) // 直线距离

    // 计算目标角度（弧度转换为度数）
    const angleInRadians = Math.atan2(dy, dx) // 返回的是弧度
    const angleInDegrees = (angleInRadians * 180) / Math.PI // 将弧度转换为度数

    // 如果AGV已经到达目标位置，则停止移动
    if (distanceToTarget === 0) {
      this.arriveDestination()
      return
    }

    // 计算在40ms（0.04s）内AGV能走的距离
    const timeInterval = 0.04
    const distancePerStep = this.speed * timeInterval * SimulationSpeed.getSpeed // 计算每50ms AGV可以移动的距离

    // 如果目标距离小于AGV在50ms内能走的距离，就直接到目标位置
    if (distanceToTarget <= distancePerStep) {
      this.x = this.targetX
      this.y = this.targetY
    } else {
      // 计算单位向量
      const moveRatio = distancePerStep / distanceToTarget
      this.x += dx * moveRatio
      this.y += dy * moveRatio
    }

    messageTransfer('workerPool', 'transport', {
      targetId: this.id,
      x: this.x,
      y: this.y,
      angle: angleInDegrees
    })

    setTimeout(() => {
      this.moving()
    }, 40)
  }

  //到达目的地
  arriveDestination() {
    if (this.taskType === 'assist') {
      //执行协助任务
      messageTransfer('workerPool', 'recycle', {
        targetId: this.id
      })
      messageTransfer('style', null, {
        targetId: this.target.id,
        style: {
          icon: 'nodeMachineWithPeople'
        }
      })
    } else if (this.taskType === 'clean') {
      //执行清洁任务
      messageTransfer('style', null, {
        targetId: this.target.id,
        style: {
          backgroundColor: '#ffffff9c'
        }
      })
      this.target.eventWindow('delProduct', null)
      this.target.eventWindow('status', 'idle')
      this.returnWorkerPool()
    } else if (this.taskType === 'maintenance') {
      schedule(
        this.maintenanceTime,
        () => {
          //执行维护任务
          messageTransfer('style', null, {
            targetId: this.target.id,
            style: {
              backgroundColor: '#ffffff9c'
            }
          })
          this.target.eventWindow('rework', null)
          //返程
          this.returnWorkerPool()
        },
        'maintenance'
      )
    } else if (this.taskType === 'return') {
      this.workerPool.returnHome(this.id)
    }
  }

  //返回工人池
  returnWorkerPool() {
    //情节完毕，开始返程
    this.taskType = 'return'
    this.targetX = this.workerPool.x
    this.targetY = this.workerPool.y
    this.moving()
  }
}

export default Worker
